import { config, isCompleteURL, requestBefore, requestAfter } from './config'
class Request {
    //默认配置
    [config] = {
        baseURL: '/api',
        header: {
            'content-type': 'application/json'
        },
        method: 'GET',
        dataType: 'json',
        responseType: 'text'
    }
    //拦截器
    interceptors = {
        request: (func) => {
            if (func) 
            {
                Request[requestBefore] = func
            } 
            else 
            {
                Request[requestBefore] = (request) => request
            }
        },
        response: (func) => {
            if (func) 
            {
                Request[requestAfter] = func
            } 
            else 
            {
                Request[requestAfter] = (response) => response
            }
        }
    }

    static [requestBefore] (config) {
        return config
    }

    static [requestAfter] (response) {
        return response
    }

    static [isCompleteURL] (url) {
        return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
    }

    setConfig(func) {
        this[config] = func(this[config])
    }

    getConfig() {
        return this[config];
    }

    request (options = {}) {
        options.baseURL = options.baseURL || this[config].baseURL
        options.dataType = options.dataType || this[config].dataType
        options.url = Request[isCompleteURL](options.url) ? options.url : (options.baseURL + options.url)
        options.data = options.data
        options.header = {...options.header, ...this[config].header}
        options.method = options.method || this[config].method

        options = {...options, ...Request[requestBefore](options)}

        return new Promise((resolve, reject) => {
            options.success = function (res) {
                resolve(Request[requestAfter](res, options))
            }
            options.fail= function (err) {
                reject(Request[requestAfter](err, options))
            }
            uni.request(options)
        })
    }

    get (url, data, options = {}) {
        options.url = url
        options.data = data
        options.method = 'GET'
        return this.request(options)
    }

    post (url, data, options = {}) {
        options.url = url
        options.data = data
        options.method = 'POST'
        return this.request(options)
    }
}

export default new Request()